package org.deyang.tools.amazon;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.*;

import org.deyang.tools.amazon.pojos.AmazonResultEntry;
import org.deyang.tools.amazon.services.ItemSearchService;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;



@SuppressWarnings("serial")
public class AmazonDealsSearchEngineServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String keyword = req.getParameter("keyword");
		String searchindex = req.getParameter("searchindex");
		String pageindex = req.getParameter("pageindex");
		
		if (keyword != null && searchindex != null){
			resp.setContentType("application/json; charset=UTF-8");
			//resp.getWriter().println("Hello, world");
			ItemSearchService search = new ItemSearchService();
			JSONArray resultArray = new JSONArray();
			
			List<AmazonResultEntry> result = search.doItemSearch(keyword, searchindex, pageindex);
			Collections.sort(result, new Comparator<AmazonResultEntry>(){
				public int compare(AmazonResultEntry o1, AmazonResultEntry o2) {
					return o2.getDealRate() - o1.getDealRate();
				}
				
			});
			for (int i = 0; i < result.size(); i++){
				JSONObject entry = new JSONObject();
				AmazonResultEntry resultEntry = result.get(i);
				entry.put("title", resultEntry.getOrignialProductTitle());
				entry.put("productlink", resultEntry.getLinkURL());
				entry.put("dealrate", resultEntry.getDealRate());
				entry.put("price", resultEntry.getFormattedPrice());
				entry.put("asin", resultEntry.getAsinValue());
				entry.put("imageurl", resultEntry.getMediumImageURL());
				//entry.put("isavailablePT", resultEntry.isAvailableForPriceTracking());
				//entry.put("priceint",resultEntry.getPriceInt());
				
				resultArray.add(entry);
				
			}
			
			
			resp.getWriter().print(resultArray.toString());
			resp.getWriter().flush();

			
			
		}
		
		
		
	}
}
